/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snAnalysis;

import debug.DebugFrame;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import wave.WaveInterpreter;

/**
 *
 * @author FUJISAI
 */
public class GetBlogList {

    private ArrayList<String> starters;
    private String startPoint;
    private String localIPAddress;
    private MySQLBridge mysql;
    private int limitDB = 0;
    private String filter_method;

    public GetBlogList(boolean starter, String query) {
        /* In case of initiating the starter machine */
        if (starter == true) {
            this.startPoint = "4CpxgpElc6f19oY.sVNubnV5cw";
        } else {
            this.startPoint = "";
        }
        
        this.limitDB = Integer.parseInt(Configuration.getValue("limitDB", "100"));
        this.localIPAddress = Configuration.getValue("localIP", "192.168.1.101");
        this.filter_method = Configuration.getValue("filter_method", "dbSorting");
        
        this.starters = new ArrayList<String>();    
        this.mysql = new MySQLBridge(query);
        this.mysql.truncateTable("blog_list");
    }

    public void getStarters() {
        try {
            ResultSet result = this.mysql.getSingleField("blog_list", "blogID", "`friends`='' LIMIT " + this.limitDB);

            while (result.next()) {
                this.starters.add(result.getString("blogID"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void clearStarters() {
        this.starters = new ArrayList<String>();
    }

    public ArrayList getFriends(String localIP, String blogID) {
        ArrayList waveCode = new ArrayList<String>();
        String friendList = "";

        try {
            String url = "http://360.yahoo.com/friends-" + blogID;
            URL u = new URL(url);
            BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream()));
            String line;
            int endNick;

            Filter bF = new Filter(this.filter_method);
            GenerateWaveCode gen = new GenerateWaveCode(true);

            if (bF.getOutputIP(blogID).compareTo(localIP) == 0) {
                this.mysql.addToDB("blog_list", "blogID", blogID, "friends", "");
            }

            int count = 0;
            while ((line = in.readLine()) != null) {

                if (line.indexOf("class=\"user-name") > 0) {

                    int startNick = line.indexOf("profile-") + 8;
                    endNick = (line.indexOf("-", startNick) > 0 && line.indexOf("-", startNick) < line.indexOf("\"", startNick)) ? line.indexOf("-", startNick) : line.indexOf("\"", startNick);
                    String friend_blog_id = line.substring(startNick, endNick);

                    String IPdetermined = bF.getOutputIP(friend_blog_id);
                    if (IPdetermined.compareTo(localIP) == 0) {
                        this.mysql.addToDB("blog_list", "blogID", friend_blog_id, "friends", "");
                    } else {
                        waveCode.add(gen.sendNodeWave(IPdetermined, friend_blog_id));
                    }
                    if (count == 0) {
                        friendList += friend_blog_id;
                    } else {
                        friendList += ";" + friend_blog_id;
                    }
                    count++;
                }
            }

            this.mysql.updateDB("blog_list", "friends", friendList, "`blogID`='" + blogID + "'");

            return waveCode;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return null;
    }

    public static void main(String args[]) {

        String query = "CREATE TABLE IF NOT EXISTS `blog_list` (" +
                "`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ," +
                "`blogID` VARCHAR( 100 ) NOT NULL ," +
                "`friends` TEXT ," +
                "`NumF` int( 11 ) ," +
                "`DMax` int( 11 ))";

        GetBlogList blog = new GetBlogList(false, query);

        /**
         * create WI instance and
         * Start some init process
         */
        WaveInterpreter win = new WaveInterpreter().getInstance();
        DebugFrame db=new DebugFrame();
        win.start();

        String createRepresenterNode = "CR(@#`" + blog.localIPAddress + "')";
        win.injectWave(createRepresenterNode);
        /**
         * end do init process
         */

        ArrayList code = new ArrayList<String>();
        if (blog.startPoint.compareTo("") != 0) {
            code = blog.getFriends(blog.localIPAddress, blog.startPoint);

            for (int j = 0; j < code.size(); j++) {
                win.injectWave(code.get(j).toString());
            }
        }

        while (true) {
            blog.getStarters();

            for (int i=0;i<blog.starters.size();i++) {
                code = blog.getFriends(blog.localIPAddress, blog.starters.get(i).toString());

                for (int j = 0; j < code.size(); j++) {
                    win.injectWave(code.get(j).toString());
                }
            }
            blog.clearStarters();
        }
    }
}
